package jmsTopic;

import java.io.BufferedWriter;
import java.io.FileWriter;

import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.ObjectMessage;
import javax.jms.TextMessage;

public class Listener implements MessageListener {

	private static final String fileName = "D:/LO54_PROJET/PROJET_LO54/log";
	
	@Override
	public void onMessage(Message message) {
		TextMessage msg = null;
		ObjectMessage objMsg = null;
		
		try {
			if(message instanceof TextMessage){
				msg = (TextMessage) message;
				System.out.println("Reading a TextMessage:" + msg.getText());
				
				// enregistrer les messages dans un log fichier
				FileWriter fstream = new FileWriter(fileName, true);
				BufferedWriter out = new BufferedWriter(fstream);
				out.append("Received a TextMessage:" + msg.getText());
				out.newLine();
				out.close();
				
			} else if (message instanceof ObjectMessage){
				objMsg = (ObjectMessage) message;
				OneMessage newMsg = (OneMessage) objMsg.getObject();
				System.out.println("Reading an ObjectMessage:" + newMsg.getFirstname() + " " + newMsg.getLastname() + " has just registered with a login: " + newMsg.getLogin());
				
				// enregistrer les messages dans un log fichier
				FileWriter fstream = new FileWriter(fileName, true);
				BufferedWriter out = new BufferedWriter(fstream);
				out.append("Received an ObjectMessage:" + newMsg.getFirstname() + " " + newMsg.getLastname() + " has just registered with a login: " + newMsg.getLogin());
				out.newLine();
				out.close();
				
			} else {
				System.out.println("Message is not a TextMessage");
			}
		} catch (JMSException e) {
			System.out.println("JMSException in onMessage():" + e.toString());
		} catch (Throwable t) {
			System.out.println("JMSException in onMessage():" + t.toString());
		}
		
	}

}
